//
//  BattleRankingView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 2. 5..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "BattleRankingView.h"

@implementation BattleRankingView
@synthesize responseData, imageURL, itemArray, dateString;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = ColorFromRGB(0x413c43);
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        itemArray = [[NSMutableArray alloc] init];
        
        [self makeObject:frame];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)makeObject:(CGRect)frame{
    
    if (deviceIOS7) {
        
        UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(0, -20, mySize.width, 20)];
        bgview.backgroundColor = ColorFromRGB(0xe9e9e9);
        [self addSubview:bgview];
    }
    
    //title
    self.titleLabel.text = NSLocalizedString(@"battleRanking", @"");
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self setSubTitleIcond:[UIImage imageNamed:@"icon_battle_ranking"] andTitle:nil];
    
    
    //table
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bodyView.frame.size.width, self.bodyView.frame.size.height)];
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.bodyView addSubview:mTableView];
    
    topMoveButton = [[UIButton alloc] initWithFrame:CGRectMake(mTableView.frame.size.width-10-35, mTableView.frame.size.height-44-35-5, 35, 35)];
    [topMoveButton setImage:[UIImage imageNamed:@"btn_top"] forState:UIControlStateNormal];
    [topMoveButton addTarget:self action:@selector(topMoveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bodyView addSubview:topMoveButton];
}

#pragma mark - 위로가기
-(void)topMoveButtonAction:(id)sender{
    [mTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 뒤로
-(void)backButtonAction:(id)sender{
    [appDelegate removeActivity];
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    [vController removeBattleRankingView];
}

#pragma mark - 몇주차인지 알아내기
-(NSString*)stringDate:(NSString*)string{
    
    NSLog(@"date string : %@",string);
    
    NSArray *array = [string componentsSeparatedByString:@"."];
    int month = [[array objectAtIndex:1] intValue];
    int week = [[array objectAtIndex:2] intValue];
    
    string = languagesKorean ? [NSString stringWithFormat:@"%d월 %d주차 무한배틀순위",month,week] :
    [NSString stringWithFormat:@"%d th week %@, Battle winner",week,[self monthInEnglish:month]];
    
    return string;
}

-(NSString*)monthInEnglish:(NSInteger)month{
    
    NSString *string = nil;
    if (month == 1) {
        string = @"Jan";
    }else if (month == 2){
        string = @"Feb";
    }else if (month == 3){
        string = @"Mar";
    }else if(month == 4){
        string = @"Apr";
    }else if (month == 5){
        string = @"May";
    }else if (month == 6){
        string = @"Jun";
    }else if(month == 7){
        string = @"Jul";
    }else if(month == 8){
        string = @"Aug";
    }else if (month == 9){
        string = @"Sep";
    }else if (month == 10){
        string = @"Oct";
    }else if (month == 11){
        string = @"Nov";
    }else if (month == 12){
        string = @"Dec";
    }
    return string;
}

#pragma mark - click
-(void)listLeftButtonClick:(id)sender{
    
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewController:button.tag];
    
}

-(void)listRightButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewController:button.tag];
}

-(void)appearPhotoViewController:(NSInteger)issueIndex{
    
    NSString *starID = [[self.itemArray objectAtIndex:issueIndex] objectForKey:@"star_id"];
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    
    photoController.parentClassIndex = 2;
    photoController.adCount = appDelegate.issueAdCount; //일단 이렇게 해놓자
    photoController.mDelegate = self;
    photoController.dateString = self.dateString;
    photoController.issuesList = self.itemArray;
    photoController.analyticsAction = ANA_ACT_BATTLE;
    photoController.analyticsLabelDetail = ANA_LAB_Battle_Photo;
    photoController.analyticsLabelWhole = ANA_LAB_Battle_Photo_Whole;
    [photoController setIssueIndex:issueIndex];
    [photoController requestBattleWithDate:self.dateString andStarID:starID];
    
    [vController presentModalViewController:photoController animated:YES];
}


#pragma mark - 페이지

-(void)loadNextPage{
    
    if (isEnd) {
        
        [self requestDate:self.dateString andPage:currentPage];
    }else{
        //마지막페이지임
        [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
    }
}

#pragma mark - 로딩

-(void)activityViewAnimationStartOnTop:(BOOL)yn{
    CGPoint point = yn ? CGPointMake(mySize.width*0.5f, mTableView.frame.origin.y+30) : CGPointMake(mySize.width*0.5f, mTableView.frame.origin.y+mTableView.frame.size.height-50);
    [appDelegate appearActivityOnPoint:point];
}

-(void)activityViewAnimationStop{
    [appDelegate removeActivity];
}

#pragma mark - 네트워크

-(void)requestDate:(NSString*)date andPage:(NSInteger)page{
    
    currentPage = page;
    if (page == 1) {
        [self.itemArray removeAllObjects];
    }
    NSString *dataStr = [NSString stringWithFormat:@"page=%ld&date=%@&lang=%@&pagesize=100",(long)page,date,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_RANKING,dataStr];
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"배툴주간순위 네트워크 요청 : %@",url);
            }
            
            [mTableView reloadData];
            
        }
    }
}


#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
//    NSLog(@"배틀순위 : %@",resultDictionary);
    
    self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
    NSString *strDate = ([appDelegate checkObject:[resultDictionary objectForKey:@"date"]]) ? [resultDictionary objectForKey:@"date"] : nil;
    
//    self.subTitleLabel.text = [self stringDate:strDate];
    self.subTitleLabel.text = [resultDictionary objectForKey:@"date_str"];
    
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            
            NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
            
            if (items) {
                [self.itemArray addObjectsFromArray:items];
//                NSLog(@"지난배틀순위리스트 : %@",self.itemArray);
            }
            
            currentPage++;
            isEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
            
            [mTableView reloadData];
            
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    NSLog(@"스타 네트워크 요청 실패 : %@",error);
}

#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger numberOfRows = ([self.itemArray count]%2 == 0) ? (int)([self.itemArray count]/2) : (int)([self.itemArray count]/2)+1;
    return numberOfRows;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 146;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"BattleRankingCell";
    ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self;
    }
    
    
    NSString *first, *second;
    NSString *firstURL, *secondURL;
    
    cell.winIcon.hidden = (indexPath.row != 0);
    
    
    if ((indexPath.row*2) < [self.itemArray count]) {
        
        //재사용시 기존 이미지 가림
        if (!cell.leftImage.image || cell.leftImage.tag != indexPath.row) {
            cell.leftImage.image = nil;
        }
        
        NSDictionary *dic = [self.itemArray objectAtIndex:indexPath.row*2];
//        NSLog(@"배틀랭킹 : %@",dic);
        
        first = [dic objectForKey:@"name"];
        firstURL = [NSString stringWithFormat:@"%@%@",self.imageURL,[dic objectForKey:@"thumb_url"]];
        cell.leftImage.tag = indexPath.row;
        cell.leftButton.tag = indexPath.row*2;
        cell.leftNumberLabel.text = [NSString stringWithFormat:@"%d",(indexPath.row*2)+1];
        [cell.leftButton addTarget:self action:@selector(listLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        NSString *win = [dic objectForKey:@"win_cnt"];
        NSString *lose = [dic objectForKey:@"lose_cnt"];
        [cell setLeftWinString:win andLoseString:lose];
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[dic objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
            
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = image;
                [appDelegate effectFaceoutTargetView:cell.leftImage];
            }
        } errorBlock:^{
            
            if (cell.leftImage.tag == indexPath.row) {
                
                cell.leftImage.image = nil;
            }
        }];
    }
    if ((indexPath.row*2)+1 < [self.itemArray count]) {
        
        //재사용시 기존 이미지 가림
        if (!cell.rightImage.image || cell.rightImage.tag != indexPath.row) {
            cell.rightImage.image = nil;
        }
        
        NSDictionary *dic = [self.itemArray objectAtIndex:(indexPath.row*2)+1];
        
        second = [dic objectForKey:@"name"];
        secondURL = [NSString stringWithFormat:@"%@%@",self.imageURL,[dic objectForKey:@"thumb_url"]];
        cell.rightImage.tag = indexPath.row;
        cell.rightButton.tag = (indexPath.row*2)+1;
        cell.rightNumberLabel.text = [NSString stringWithFormat:@"%d",((indexPath.row*2)+1)+1];
        [cell.rightButton addTarget:self action:@selector(listRightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        NSString *win = [dic objectForKey:@"win_cnt"];
        NSString *lose = [dic objectForKey:@"lose_cnt"];
        [cell setRightWinString:win andLoseString:lose];
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[dic objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
            
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = image;
                [appDelegate effectFaceoutTargetView:cell.rightImage];
            }
            
        } errorBlock:^{
            
            if (cell.rightImage.tag == indexPath.row) {
                
                cell.rightImage.image = nil;
            }
        }];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell cellOfIssueWithHotList:nil andFirstTitle:first andSecondTitle:second];
    cell.leftTitle.textAlignment = cell.rightTitle.textAlignment = NSTextAlignmentCenter;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (!duringNetwork && ([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
        
        
        [self loadNextPage];
        [mTableView setContentOffset:CGPointMake(0, [scrollView contentOffset].y+60)];
//        [self activityViewAnimationStartOnTop:NO];
    }else{
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
//        topMoveButton.hidden = NO;
    }
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
    }
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:YES];
    topMoveButton.hidden = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
//    if (scrollView.contentOffset.y < -60) {
//        [mTableView setContentOffset:CGPointMake(0, -60)];
//    }
}

-(void)scrollOffsetChange:(id)userInfo{
    
}



@end
